<?php
namespace home\Model;
use Think\Model;
class ChatModel extends Model{

    public function admin_chat($admin_id,$user_id,$content){

        $chat['type'] = 1;
        $chat['chat_id'] = $this->find_chat($admin_id,$user_id);
        $chat['fm'] = $admin_id;
        $chat['t'] = $user_id;
        $chat['time'] = time();
        $chat['is_read'] = 0;
        $chat['content'] = json_encode(array("content"=>$content),JSON_UNESCAPED_SLASHES+JSON_UNESCAPED_UNICODE);
        $this->add($chat);
    }

    public function admin_url($admin_id,$user_id,$content,$url){

        $chat['type'] = 11;
        $chat['chat_id'] = $this->find_chat($admin_id,$user_id);
        $chat['fm'] = $admin_id;
        $chat['t'] = $user_id;
        $chat['time'] = time();
        $chat['is_read'] = 0;
        $chat['content'] = json_encode(array("content"=>$content,"url"=>$url),JSON_UNESCAPED_SLASHES+JSON_UNESCAPED_UNICODE);
        $this->add($chat);
    }

    public function create_admin_chat($uid)
    {
        $admin = M('user')->where('id < 0')->select();
        foreach ($admin as $key => $value) {
            $chat['user1'] = $admin[$key]['id'];
            $chat['user2'] = $uid;
            $chat['time'] = time();
            $chat['content'] = "发起了私聊";
            M('chat')->add($chat);
        }

    }

    public function get_chat_list($user_id,$like,$page=1,$pagesize=20,$type=""){
        if ($type == "all") {
            $data = M('chat as a')
            ->join('
                left join user as b on a.user1 = b.id
                left join user as c on a.user2 = c.id
            ')
            ->field('a.id ,
                a.time ,
                a.content,
                b.id as bid,
                b.head_ico as bhead,
                b.nick_name as bname,
                c.id as cid,
                c.head_ico as chead,
                c.nick_name as cname')
            ->where('(a.user1 = '.$user_id.' or a.user2 = '.$user_id.')')
            ->page($page,$pagesize)
            ->order('a.time desc')
            ->select();
            $data = $this->parse_chats($data,$user_id);
        }else{
            $where = '(a.user1 = '.$user_id.' or a.user2 = '.$user_id.') and a.user1 > 0 and a.user2 > 0';

            $data['admin_chat'] = M('chat as a')
                ->join('
    				left join user as b on a.user1 = b.id
    				left join user as c on a.user2 = c.id
    			')
                ->field('a.id ,
    				a.time ,
    				a.content,
    				b.id as bid,
    				b.head_ico as bhead,
    				b.nick_name as bname,
    				c.id as cid,
    				c.head_ico as chead,
    				c.nick_name as cname')
                ->where('a.user1 in (-2,-3,-4,-5,-6) and a.user2 = '.$user_id)
                ->page($page,$pagesize)
                ->order('a.time desc')
                ->select();

            $data['admin_chat2'] = M('chat as a')
                ->join('
    				left join user as b on a.user1 = b.id
    				left join user as c on a.user2 = c.id
    			')
                ->field('a.id ,
    				a.time ,
    				a.content,
    				b.id as bid,
    				b.head_ico as bhead,
    				b.nick_name as bname,
    				c.id as cid,
    				c.head_ico as chead,
    				c.nick_name as cname')
                ->where('a.user1 in (-1,-7,-8) and a.user2 = '.$user_id)
                ->page($page,$pagesize)
                ->order('a.time desc')
                ->select();

            $data['user_chat'] = M('chat as a')
                ->join('
    				left join user as b on a.user1 = b.id
    				left join user as c on a.user2 = c.id
    			')
                ->field('a.id ,
    				a.time ,
    				a.content,
    				b.id as bid,
    				b.head_ico as bhead,
    				b.nick_name as bname,
    				c.id as cid,
    				c.head_ico as chead,
    				c.nick_name as cname')
                ->where($where)
                ->page($page,$pagesize)
                ->order('a.time desc')
                ->select();

            $data['user_chat'] = $this->parse_chats($data['user_chat'],$user_id);
            $data['admin_chat'] = $this->parse_chats($data['admin_chat'],$user_id);
            $data['admin_chat2'] = $this->parse_chats($data['admin_chat2'],$user_id);
        }
        return $data;
    }

    public function parse_chats($data,$user_id)
    {
        foreach ($data as $key => $value) {


            $data[$key]['no_read'] = M('msg')->where('chat_id = '.$data[$key]['id'].' and t = '.$user_id.' and is_read = 0')->count();

            if ($data[$key]['bid'] == $user_id) {
                $data[$key]['nick_name'] = $data[$key]['cname'];
                $data[$key]['head_ico'] = $data[$key]['chead'];
                $data[$key]['uid'] = $data[$key]['cid'];

            }else if ($data[$key]['cid'] == $user_id) {
                $data[$key]['nick_name'] = $data[$key]['bname'];
                $data[$key]['head_ico'] = $data[$key]['bhead'];
                $data[$key]['uid'] = $data[$key]['bid'];
            }
            unset($data[$key]['bname'],$data[$key]['cname'],$data[$key]['bhead'],$data[$key]['chead'],$data[$key]['bid'],$data[$key]['cid']);
            $data[$key]['time'] = friendlyDate($data[$key]['time']);
        }
        return $data;

    }

    public function get_no_read_number($user_id){
        $count = M('chat')
            ->where('is_read = 0 and t = '.$user_id)
            ->count();
        return $count;
    }

    public function find_chat($user1,$user2){
        $chat = M('chat')->where('(user1 = '.$user1.' and user2 = '.$user2.') or (user2 = '.$user1.' and user1 = '.$user2.')')->find();
        if ($chat != null) {
            return $chat['id'];
        }

        $chat['user1'] = $user1;
        $chat['user2'] = $user2;
        $chat['time'] = time();
        $chat['content'] = "发起了私聊";
        $id = M('chat')->add($chat);
        return $id;
    }

    public function get_new_msg($chat_id,$max_msg_id,$user_id){
        $chat = M('chat')->where('id = '.$chat_id)->find();
        $c['is_read'] = 1;
        M('msg')->where('t = '.$user_id.' and chat_id = '.$chat_id.' and is_read = 0')->save($c);
        $user1 = M('user')->field('id , nick_name ,head_ico')->where('id = '.$chat['user1'])->find();
        $user2 = M('user')->field('id , nick_name ,head_ico')->where('id = '.$chat['user2'])->find();
        if ($user1['id'] == $user_id) {
            $data['me'] = $user1;
            $data['you'] = $user2;
        }else{
            $data['me'] = $user2;
            $data['you'] = $user1;
        }
        $data['chat_id'] = $chat_id;
        $data['max_msg_id'] = M('msg')->where('chat_id = '.$chat_id)->max('id');
        $data['chat'] = M('msg as a')
            ->field('a.id , a.type , a.content , a.fm , a.t , a.time ')
            ->where('a.chat_id = '.$chat_id.' and id > '.$max_msg_id)
            ->order('a.id desc')
            ->select();

        foreach ($data['chat'] as $key => $value) {
            if ($data['chat'][$key]['fm'] == $data['me']['id']) {
                $data['chat'][$key]['from_me'] = 1;
            }else{
                $data['chat'][$key]['from_me'] = 0;
            }

            $data['chat'][$key]['content'] = json_decode($data['chat'][$key]['content'],ture);

            $data['chat'][$key]['time_str'] = friendlyDate($data['chat'][$key]['time']);
        }
        sort($data['chat']);
        //var_dump($data['chat']);
        return $data;
    }

    public function get_chat($chat_id,$page=1,$pagesize=20,$user_id){
        $chat = M('chat')->where('id = '.$chat_id)->find();
        $c['is_read'] = 1;
        M('msg')->where('t = '.$user_id.' and chat_id = '.$chat_id.' and is_read = 0')->save($c);
        $user1 = M('user')->field('id ,uuid , nick_name ,head_ico')->where('id = '.$chat['user1'])->find();
        $user2 = M('user')->field('id ,uuid , nick_name ,head_ico')->where('id = '.$chat['user2'])->find();
        if ($user1['id'] == $user_id) {
            $data['me'] = $user1;
            $data['you'] = $user2;
        }else{
            $data['me'] = $user2;
            $data['you'] = $user1;
        }
        $data['chat_id'] = $chat_id;
        $data['max_msg_id'] = M('msg')->where('chat_id = '.$chat_id)->max('id');
        $data['chat'] = M('msg as a')
            ->field('a.id , a.type , a.content , a.fm , a.t , a.time ')
            ->where('a.chat_id = '.$chat_id)
            ->order('a.id desc')
            ->page($page,$pagesize)
            ->select();

        foreach ($data['chat'] as $key => $value) {
            if ($data['chat'][$key]['fm'] == $data['me']['id']) {
                $data['chat'][$key]['from_me'] = 1;
            }else{
                $data['chat'][$key]['from_me'] = 0;
            }

            $data['chat'][$key]['content'] = json_decode($data['chat'][$key]['content'],ture);

            $data['chat'][$key]['time_str'] = friendlyDate($data['chat'][$key]['time']);
        }
        sort($data['chat']);
        //var_dump($data['chat']);
        return $data;
    }

    public function add($data){

        $data['time'] = time();

        $from_user = M('user')->where('id = '.$data['fm'])->find();
        $to_user = M('user')->where('id = '.$data['t'])->find();

        $id = M('msg')->add($data);
        $to_user_no_read = M('msg')->where('t = '.$data['t'].' and is_read = 0')->count();

        $chat['time'] = time();
        if ($data['type'] == 1){
            $json = json_decode($data['content'],true);
            $chat['content'] = $json['content'];

        }else if ($data['type'] == 2){
            $chat['content'] = "[图片]";
        }else if ($data['type'] == 3){
            $chat['content'] = "[语音]";
        }else if ($data['type'] == 11){
            $json = json_decode($data['content'],true);
            $chat['content'] = $json['content'];
        }
        $push_msg  = $chat['content'];

        M('chat')->where('id = '.$data['chat_id'])->save($chat);

        A('Emqx')->send("user".$to_user['token'],'{"msg":"'.$from_user['nick_name'].'：'.$push_msg.'","num":"'.$to_user_no_read.'","type":"msg","content":'.$data['content'].'}');
        if ($to_user['id'] == -8) {
            //给文件助手发信息
            if ($data['type'] == 2) {
                A('Emqx')->send("user".$from_user['token'],'{"msg":"'.$from_user['nick_name'].'：'.$push_msg.'","num":"'.$to_user_no_read.'","type":"mobile_to_pc_file_img","content":'.$data['content'].'}');
            }
            
            # code...
        }

        return $id;
        // $from_user = M('user')->where('id = '.$data['fm'])->find();
        // $to_user = M('user')->where('id = '.$data['t'])->find();
        // //$num = M('chat')->where('t = '.$data['t'].' and is_read = 0')->count();

        // $app = M('app_list')->where('id = '.$to_user['app_type'])->find();
        // if ($app['type'] == 1) {
        // 	$fm_user = M('user')->where('id = '.$data['fm'])->find();
        //        $fm = $fm_user['nick_name'].' '.$fm_user['real_name'];
        //        $wlmq_id = $to_user['wlmq_id'];
        //        $res = A('Send')->msg($wlmq_id,$num,$fm);
        // 	return $res;
        // }else{
        // 	if ($data['type'] == 1) {
        // 		$res = A('Xcx')->push_new_msg($to_user['id'],$from_user['nick_name'],$data['content']);
        // 	}elseif ($data['type'] == 2){
        // 		$res = A('Xcx')->push_new_msg($to_user['id'],$from_user['nick_name'],'发来了一张图片');
        // 	}elseif ($data['type'] == 3){
        // 		$res = A('Xcx')->push_new_msg($to_user['id'],$from_user['nick_name'],'发来了一段语音');
        // 	}elseif ($data['type'] == 4){
        // 		$res = A('Xcx')->push_new_msg($to_user['id'],$from_user['nick_name'],'发来了一段视频');
        // 	}elseif ($data['type'] == 5){
        // 		$res = A('Xcx')->push_new_msg($to_user['id'],$from_user['nick_name'],'发来了一个位置');
        // 	}elseif ($data['type'] == 6){
        // 		$res = A('Xcx')->push_new_msg($to_user['id'],$from_user['nick_name'],'发来了一枚红包');
        // 	}

        // }




    }
}